package leetcode

import java.util.LinkedList
import java.util.Queue
import kotlin.math.log

/**
 * https://leetcode.cn/problems/string-to-integer-atoi/
 */
class Solution_8 {
    fun compare(number:String,flag:Int):Int{
        if (number.isEmpty()) return 0
        val limit = if (flag< 0) "2147483648" else "2147483647"
        if (number.length > limit.length){
            return if (flag < 0){
                -2147483648
            }else{
                2147483647
            }
        }
        if (number.length < limit.length){
            return if (flag < 0){
                "-${number}".toInt()
            }else{
                number.toInt()
            }
        }
        val len = limit.length
        for (i in 0 until len) {
            if (number[i] > limit[i]) {
                return if (flag < 0){
                    -2147483648
                }else{
                    2147483647
                }
            }else if(number[i] < limit[i]){
                break
            }

        }
        return if (flag < 0){
            "-${number}".toInt()
        }else{
            number.toInt()
        }
    }
    fun myAtoi(s: String): Int {
        val queue = StringBuilder()
        var flag = 0
        for (c in s) {
            if (flag == 0){
                if (c == ' ') continue
                if (c == '+') {
                    flag = 1
                    continue
                }
                if (c == '-') {
                    flag = -1
                    continue
                }
            }
            if (queue.isEmpty() && c == '0'){
               if(flag ==0) flag = 1
                continue
            }
            if (c in '0'..'9') {
                if(flag ==0) flag = 1
                queue.append(c)
            }else {
                break
            }
        }
       return compare(queue.toString(),flag)
    }

}

fun main() {
//    println(Solution_8().myAtoi("32") == 32)
    println(Solution_8().myAtoi("-042") == -42)
    println(Solution_8().myAtoi("200000000000000000000000000000") == 2147483647)
    println(Solution_8().myAtoi("   -200000000000000000000000000000") == -2147483648)
//    println(Solution_8().myAtoi("1337c0d3") == 1337)
//    println(Solution_8().myAtoi("0-1") == 0)
//    println(Solution_8().myAtoi("words and 987") == 0)
//    println("hello world")
}